package com.yangzb.java.sample.kugou;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yangzb.java.sample.xmly.UrlParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yzb
 */
public class Download {
    private String albumId;
    private String path;
    private String dfid;
    private String mid;
    public static final String URL = "https://www.kugou.com/ts/album/{}/p{}.html";
    public static final String URL_TRACK = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&appid=1014&dfid={}&mid={}&platid=4&from=111&encode_album_audio_id={}&_={}";

    public static final Map<String, List<String>> HEADERS = new HashMap() {{
        put("User-Agent", ListUtil.of("Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 Edg/99.0.4844.51"));
//        put("Host", ListUtil.of("m.ximalaya.com"));
        put("cookie", ListUtil.of("kg_mid=b8dae109b6b509e5618560ee94d240d6; kg_dfid=4FIPtE0kLVju3SGkcx07rcpg; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; kg_mid_temp=b8dae109b6b509e5618560ee94d240d6; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1673517660,1673576036; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1673576036"));
        put("referer", ListUtil.of("https://www.kugou.com/"));
    }};

    public static final Map<String, List<String>> HEADERS_TRACK = new HashMap() {{
        put("User-Agent", ListUtil.of("Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 Edg/99.0.4844.51"));
//        put("Host", ListUtil.of("mpay.ximalaya.com"));
        put("cookie", ListUtil.of("kg_mid=b8dae109b6b509e5618560ee94d240d6; kg_dfid=4FIPtE0kLVju3SGkcx07rcpg; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; kg_mid_temp=b8dae109b6b509e5618560ee94d240d6; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1673517660,1673576036; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1673576036"));
        put("referer", ListUtil.of("https://www.kugou.com/"));
    }};

    public Download(String albumId, String path,String dfid,String mid) {
        this.albumId = albumId;
        this.path = path;
        this.dfid = dfid;
        this.mid = mid;
    }

    public void run(String place) throws Exception {
        getTrackDetailInfos();
        int index = 1;
        for (Object o : allTrack) {
            JSON track = (JSON)o;
            String id = StrUtil.toString(track.getByPath("encode_album_audio_id"));
            String title = StrUtil.toString(track.getByPath("title"));

            HttpRequest request = HttpUtil.createGet(StrUtil.format(URL_TRACK,dfid,mid, id, System.currentTimeMillis()));
            request.header(HEADERS_TRACK);
            HttpResponse response = request.execute();
            JSON parse = JSONUtil.parse(response.body());
            String url = StrUtil.toString(parse.getByPath("data.play_url"));
            if(StrUtil.isBlank(url)){
                System.out.println(JSONUtil.toJsonPrettyStr(parse));
                FileUtil.writeString(title,path+"/log.txt","utf-8");
                continue;
            }
            TimeUnit.MILLISECONDS.sleep(200);
            String extName = "."+FileUtil.extName(url);
            HttpUtil.downloadFile(url,path+"/"+title.replaceAll(place,"")+extName);
            System.out.println(id+":"+title+":"+url+">>"+index);
            index++;
        }
    }

    private JSONArray allTrack = JSONUtil.createArray();

    public void getTrackDetailInfos() throws Exception {
        int page = 1;
        int totalCount = 0;
        while (true) {
            HttpRequest request = HttpUtil.createGet(StrUtil.format(URL, this.albumId, page));
            request.header(HEADERS);
            HttpResponse response = request.execute();
            String listContent = response.body();
            Document parse = Jsoup.parse(listContent);
            Elements lis = parse.select("div.mod_list  li.mod_list_li");
            if(lis == null ||lis.size()==0){
                System.out.println(StrUtil.format("总：{}个",totalCount));
                break;
            }
            for (Element li : lis) {
                String encode_album_audio_id = li.attr("data-encode_album_audio_id");
                JSONObject json = JSONUtil.createObj();
                json.set("encode_album_audio_id",encode_album_audio_id);
                json.set("title",li.select("span.s4_mod_list_li_sp1").first().text());
                allTrack.add(json);
                totalCount ++;
            }
            page ++;
            TimeUnit.MILLISECONDS.sleep(500);
        }
    }
}
